<template>
  <div>
    <div class="main-list-box new-rulesd">
      <div v-for="(item, index) in ruleList" :key="index">
        <div class="main-item-box">
          <div class="flex items-center justify-between">
            <p class="list-title">时间组{{ index + 1 }}</p>
            <div
              v-if="ruleList.length > 1"
              class="flex items-center del-box"
              @click="delRule(item, index)"
            >
              <e v-html="delSvg('#999999')"></e>
              <e v-html="delSvg(setStyles.primaryColor)"></e>
              删除
            </div>
          </div>

          <Form ref="formRefs" name="dynamic_form_item" :model="item" :rules="formRules">
            <div class="h-58-new">
              <Form.Item label="规则名称" name="ruleName">
                <Input
                  :id="new Date().getTime()"
                  v-model:value.trim="item.ruleName"
                  class="name-input"
                  :show-count="true"
                  placeholder="请输入规则名称"
                  :maxlength="10"
                />
              </Form.Item>
              <Form.Item label="生效范围" name="area">
                <span class="select-new">
                  <Select
                    v-if="!isDisabled"
                    :id="`objectChangeRef${index}`"
                    v-model:value="item.area"
                    style="width: 100%"
                    :show-search="false"
                    :disabled="true"
                    name="area"
                    placeholder="请选择"
                    mode="multiple"
                    class="object-change"
                    :options="areaTypeList"
                    :get-popup-container="triggerNode => props.accessControlRulesRef"
                    @deselect="delArea(index)"
                  >
                    <template #dropdownRender>
                      <div class="object-change-down" @mousedown="e => e.preventDefault()">
                        <a-checkbox
                          v-model:checked="item.isAreaAll"
                          :class="
                            item.gradeIdList.length > 0 &&
                            item.gradeIdList.length < areaTypeListCheck.length
                              ? 'checkbox-no-all'
                              : ''
                          "
                          @change="changeArea(`objectChangeRef${index}`, true, index)"
                          >全部</a-checkbox
                        >
                        <a-checkbox-group
                          v-model:value="item.gradeIdList"
                          :options="areaTypeListCheck"
                          @change="val => changeArea(`objectChangeRef${index}`, false, index)"
                        />
                      </div>
                    </template>
                  </Select>
                  <Select
                    v-else
                    v-model:value="item.area"
                    style="width: 100%"
                    :show-search="false"
                    name="area"
                    :options="areaTypeList"
                    disabled
                  >
                  </Select>
                </span>
              </Form.Item>
            </div>
            <div class="time-change-box">
              <Form.Item label="时间规则" name="time">
                <span class="z-time-box-new">
                  <TimeRangePicker
                    v-model:value="item.time"
                    :get-popup-container="() => props.accessControlRulesRef"
                    :input-read-only="true"
                    format="HH:mm"
                    value-format="HH:mm"
                    @change="timeChange(index)"
                  >
                    <template #suffixIcon> </template>
                    <template #separator>
                      <span class="time-center">至</span>
                    </template>
                  </TimeRangePicker>
                  <div class="z-time-box-icon">
                    <img src="@/assets/images/rule/u_clock.png" alt="" />
                  </div>
                </span>
              </Form.Item>
              <Form.Item label="进出方向" name="accessDirection">
                <Select
                  ref="objectChangeRef"
                  v-model:value="item.accessDirection"
                  class="select-new"
                  placeholder="请选择进出方向"
                  :options="directionList1"
                  :get-popup-container="() => props.accessControlRulesRef"
                >
                </Select>
              </Form.Item>
            </div>
          </Form>
        </div>
        <span v-if="item.isErr" class="access-form-err">必填选项为空，请输入</span>
      </div>
    </div>
    <div
      :class="`flex items-center justify-center access-control-add-box ${
        ruleList.length >= 20 ? 'add-no-box' : ''
      }`"
      class="w-100"
      @click="addList"
      ><PlusOutlined class="mr-2" /> 单击此处添加
    </div>
  </div>
</template>

<script setup>
import { Form, Select, Input, TimePicker, message } from 'ant-design-vue';
import { ref, watch, computed, nextTick, defineProps, defineExpose, onMounted } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { useStore } from 'vuex';
import { getRgba } from '@/utils/validate.js';
import { delSvg } from '@/utils/svg.js';
import { getTimeGroupList, saveTimeGroup } from '@/api/ruleSetting';
const { TimeRangePicker } = TimePicker;
const store = useStore();
const studentTimeList = ref([]);
const props = defineProps({
  accessControlRulesRef: null,
  isDisabled: {
    default: false,
    type: Boolean
  },
  list: {
    default: () => [{}],
    type: Array
  }
});
const formRefs = ref(null);
// 规则列表
let ruleList = ref([
  {
    id: '',
    ruleName: '', // 规则名称
    ruleType: 1, // 0学生 1教职工
    ruleStartTime: '', // 开始时间
    ruleStopTime: '', // 结束时间
    accessDirection: '1', // 进出方向 0进 1出 1 2
    area: ['0'],
    time: [],
    direction: '1',
    isAreaAll: true,
    isErr: false
  }
]);
let gradeIdList = ref([]);
// 表单检验规则
const formRules = ref({
  ruleName: [
    { required: true, message: '请输入规则名称', trigger: ['change', 'blur'] },
    { max: 10, message: '请输入正确的规则名称' }
  ],
  area: [{ required: true, message: '请选择生效范围', trigger: ['change', 'blur'], type: 'array' }],
  time: [{ required: true, message: '请选择时间规则', trigger: ['change', 'blur'], type: 'array' }],
  accessDirection: [{ required: true, message: '请选择进出方向', trigger: 'change' }]
});
const deleteArr = ref([]);
watch(
  () => ruleList.value,
  val => {
    val.forEach(item => {
      console.log(item, '22');
      // if (item.ruleName.length && item.time.length && item.area.length) {
      //   item.isErr = false;
      // }
    });
  },
  { deep: true }
);
function validateFields() {
  console.log('走进来咯热门');
  formRefs.value.validateFields();
}
function cancelRed() {
  ruleList.value.forEach((item, index) => {
    item.isErr = false;
  });
}
onMounted(() => {
  console.log('传过来的数组是什么', props.list);
  // studentTimeList.value.forEach((item, index) => {
  //       item.time = []
  //       item.time[0] = item.ruleStartTime;
  //       item.time[1] = item.ruleStopTime;
  //     });
  GetTimeGroupList(1);
});
function GetTimeGroupList(type) {
  let data = {
    ruleType: type
  };
  getTimeGroupList(data).then(res => {
    console.log('查询宿舍时间组-里层-教师', res);
    if (res.data.code === 200 && res.data.data.length > 0) {
      ruleList.value = res.data.data;
      ruleList.value.forEach((item, index) => {
        item.time = [];
        item.time[0] = item.ruleStartTime;
        item.time[1] = item.ruleStopTime;
        item.accessDirection = item.accessDirection + '';
        item.area = ['0'];
      });
    }
  });
}
// 生效范围下拉菜单
const areaTypeList = ref([
  {
    label: '全部',
    value: '0'
  }
]);
const areaTypeListCheck = ref([]);
// 进出方向下拉菜单
const directionList1 = ref([
  {
    label: '进',
    value: '1'
  },
  {
    label: '出',
    value: '2'
  }
]);

// 定义颜色变量
const setStyles = computed(() => {
  return {
    '--primaryColor': store.state.user.primaryColor,
    primaryColor: store.state.user.primaryColor,
    backgroundColor: getRgba(store.state.user.primaryColor, 0.1)
  };
});
// 新增规则列表
const addList = () => {
  if (ruleList.value.length >= 20) return;
  ruleList.value.push({
    // id: '',
    ruleName: '', // 规则名称
    ruleType: 1, // 0学生 1教职工
    ruleStartTime: '', // 开始时间s
    ruleStopTime: '', // 结束时间
    accessDirection: '1', // 进出方向 0进 1出
    area: ['0'],
    time: [],
    direction: '1',
    isAreaAll: true,
    isErr: false
  });
  nextTick(() => {
    console.log(document.getElementsByClassName('main-list-box')[0]);
    document.getElementsByClassName('main-list-box')[0].scrollTop = 999999;
  });
};
// 删除规则
const delRule = (item, index) => {
  // ruleList.value.splice(index, 1);
  if (item.id && item.id !== null) {
    deleteArr.value.push(item.id);
  }
  ruleList.value.splice(index, 1);
};
const objectChangeRef = ref('');

// 选择生效返回
const changeArea = (vhtml, isAll, index) => {
  vhtml ? document.getElementById(vhtml).focus() : '';
  console.log(isAll, 'val');
  // let all = val.filter(item => item.length === 0);
  if (isAll) {
    if (ruleList.value[index].isAreaAll) {
      ruleList.value[index].area = ['0'];
      ruleList.value[index].gradeIdList = gradeIdList.value;
    } else {
      ruleList.value[index].area = [];
      ruleList.value[index].gradeIdList = [];
    }
  } else {
    // ruleList.value[index].areaCheck = [...ruleList.value[index].area];
    ruleList.value[index].area = [...ruleList.value[index].gradeIdList];
    if (ruleList.value[index].gradeIdList.length === gradeIdList.value.length) {
      ruleList.value[index].area = ['0'];
      ruleList.value[index].gradeIdList = gradeIdList.value;
      ruleList.value[index].isAreaAll = true;
    } else {
      ruleList.value[index].area = [...ruleList.value[index].gradeIdList];
      ruleList.value[index].isAreaAll = false;
    }
  }
};
// 删除生效范围回调
const delArea = index => {
  // ruleList.value[index].area = [];
  ruleList.value[index].gradeIdList = [...ruleList.value[index].area];
  ruleList.value[index].isAreaAll = false;
};
function timeChange(index) {
  console.log('选择的时间是什么', index);
  ruleList.value[index].ruleStartTime = ruleList.value[index].time[0];
  ruleList.value[index].ruleStopTime = ruleList.value[index].time[1];

  if (
    time_to_sec(ruleList.value[index].ruleStartTime) -
      time_to_sec(ruleList.value[index].ruleStopTime) ===
    0
  ) {
    message.error('结束时间不能等于开始时间');
    ruleList.value[index].ruleStartTime = '';
    ruleList.value[index].ruleStopTime = '';
    ruleList.value[index].time = [];
  }
}
function time_to_sec(time) {
  if (time !== null) {
    let s = '';
    let hour = time.split(':')[0];
    let min = time.split(':')[1];
    let sec = time.split(':')[2];
    s = Number(hour * 3600) + Number(min * 60);
    return s;
  }
}
function emptyDel() {
  deleteArr.value = [];
}
defineExpose({ ruleList, deleteArr, validateFields, cancelRed, GetTimeGroupList, emptyDel });
</script>

<style lang="less" scoped>
@import url('./accessControlRules.less');
.access-control-add-box:hover {
  cursor: pointer;
  border-color: v-bind('setStyles.primaryColor');
  color: v-bind('setStyles.primaryColor');
}
// .w-100 {
//   width: 100%;
// }
.h-58-new {
  height: 58px;
}
</style>
